package com.ruizhong.centercontroll.util;

import java.io.*;
import java.net.*;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.*;

public class TCPSender {

    private static ExecutorService executor = Executors.newSingleThreadExecutor();

    private static ConcurrentHashMap<String,Boolean> stringMapConnect = new ConcurrentHashMap<>();

    public static String send(String aimIpAddress, Integer aimPort, byte[] message, Boolean needReply,String wsToken) {
        try {
            final Socket socket = new Socket(aimIpAddress, aimPort);
            OutputStream outputStream = socket.getOutputStream();
            final BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            outputStream.write(message);
            outputStream.flush();
            if (needReply) {

                Future<String> futureResponse = executor.submit(() -> {
                    // 接收返回值
                    String response = in.readLine();
                    return response;
                });
                try {
                    // 尝试在1秒内获取接收结果
                    String response = futureResponse.get(1, TimeUnit.SECONDS);
                    if (response != null) {
                        System.out.println("Received response: " + response);
                    } else {
                        System.out.println("No response received or an error occurred.");
                    }
                    return response;
                } catch (TimeoutException e) {
                    System.out.println("Timeout occurred. No response received within 1 second.");
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    // 取消Future（尽管在这个例子中它可能已经被完成了）
                    futureResponse.cancel(false);
                    // 关闭执行器
                }

            }else{
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        stringMapConnect.put(wsToken,true);
                        while(stringMapConnect.get(wsToken)){
                            char[] bufferChars = new char[1024];
                            int read = 0;
                            try {
                                read = in.read(bufferChars, 0, bufferChars.length);
                                String response = new String(bufferChars,0,read);
                                System.out.println(response);
                            } catch (IOException e) {
                                e.printStackTrace();
                            }

                        }
                    }
                }).start();


            }
            return null;
        } catch (UnknownHostException e) {
            System.err.println("Server not found: " + e.getMessage());
        } catch (IOException e) {
            System.err.println("I/O error: " + e.getMessage());
        }
        return null;
    }

    public static void closeTCPConnection(String wsToken){
        stringMapConnect.put(wsToken,false);
    }
}